package scatter.schedulequartz.rest.job;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import scatter.common.rest.tools.InterfaceTool;

import java.util.Map;

/**
 * http 请求任务
 * Created by yangwei
 * Created at 2021/2/4 10:14
 */
@Slf4j
public class HttpInvokerJob extends AbstractJob implements InterfaceTool {

    public enum HttpInvokerJobDataMapKeys{
        httpUrl, httpMethod, httpHeaders, httpParams,
    }

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String doExecute(JobExecutionContext context) throws JobExecutionException {
        log.info("任务执行 mergedJobDataMap={}",context.getMergedJobDataMap().toString());
        // 获取参数
        String httpUrl = (String) context.getMergedJobDataMap().get(HttpInvokerJobDataMapKeys.httpUrl.name());
        String httpMethod = (String) context.getMergedJobDataMap().get(HttpInvokerJobDataMapKeys.httpMethod.name());
        Map<String,String> httpHeadersParam = (Map<String, String>) context.getMergedJobDataMap().get(HttpInvokerJobDataMapKeys.httpHeaders.name());
        Map<String,Object> httpParams = (Map<String, Object>) context.getMergedJobDataMap().get(HttpInvokerJobDataMapKeys.httpParams.name());
        // 封装请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        if (httpHeadersParam != null) {
            for (String key : httpHeadersParam.keySet()) {
                httpHeaders.add(key,httpHeadersParam.get(key));
            }
        }
        HttpEntity tHttpEntity = new HttpEntity(httpParams, httpHeaders);
        // 发起请求
        ResponseEntity<String> exchange = restTemplate.exchange(httpUrl, HttpMethod.resolve(httpMethod.toUpperCase()), tHttpEntity, String.class);

        HttpResult httpResult = httpResultWrap(exchange.getStatusCodeValue(), exchange.getBody(), exchange.getHeaders());

        log.info("任务执行结果 responseStatus={},responseBody={},responseHeaders={}",exchange.getStatusCodeValue(),exchange.getBody(),toJsonStr(httpResult.getHeaders()));


        return toJsonStr(httpResult);
    }
}
